package br.com.android.pubclub.web;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import br.com.android.pubclub.R;
import br.com.android.pubclub.basicas.Amizade;
import br.com.android.pubclub.basicas.Cliente;
import br.com.android.pubclub.dados.ThreadAmizadesAcoes;
import br.com.android.pubclub.dados.WsServicos;

public class BuscarClientes extends ListActivity {

	static ArrayList<Cliente> listaTodosClientes;
	EditText edtNomeBusca;
	ClientesAdapter cltsAdp;
	TextView txtMostraTodos;
	private Handler handler;
	ProgressDialog pd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tela_de_busca_generica);

		listaTodosClientes = (ArrayList<Cliente>) getIntent()
				.getSerializableExtra("listaDeClientes");
		registerForContextMenu(this.getListView());

		edtNomeBusca = (EditText) findViewById(R.id.edtBusca);
		edtNomeBusca.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				ArrayList<Cliente> listaClientesBusca = new ArrayList<Cliente>();

				String nomeBusca = edtNomeBusca.getText().toString()
						.toLowerCase().trim();

				for (Cliente c : listaTodosClientes) {

					if (c.getNome().trim().toLowerCase().contains(nomeBusca)) {

						listaClientesBusca.add(c);
					}

				}
				cltsAdp = new ClientesAdapter(listaClientesBusca);
				setListAdapter(cltsAdp);

			}
		});

	}

	public void refresh(View v) {

		Handler hand = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case ThreadAmizadesAcoes.EXECUTANDO:

					pd = new ProgressDialog(BuscarClientes.this);
					pd.setMessage("Enviando...");
					pd.show();

					break;

				case ThreadAmizadesAcoes.EXIBINDO:

					listaTodosClientes = (ArrayList<Cliente>) msg.getData()
							.getSerializable("listaDeClientes");
					pd.dismiss();

					break;
				}
			}
		};

		RefreshingThread rt = new RefreshingThread(hand);
		rt.start();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		if (v.getId() == android.R.id.list) {
			AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
			Cliente cli = (Cliente) getListView().getItemAtPosition(
					info.position);
			menu.setHeaderTitle(cli.getNome());
			String[] menuItens = getResources().getStringArray(
					R.array.opcoesClienteContextMenu);
			int itemId = 0;
			for (String item : menuItens) {

				menu.add(Menu.NONE, itemId, Menu.NONE, item);
				itemId++;
			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		Cliente clienteClicado = (Cliente) getListView().getItemAtPosition(
				info.position);

		switch (item.getItemId()) {
		case 0:

			Intent it = new Intent(this, VerPerfil.class);
			it.putExtra("clientePerfil", clienteClicado);
			startActivity(it);
			return true;
		case 1:

			solicitarAmizade(clienteClicado);

			return true;
		case 2:

			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	private void solicitarAmizade(Cliente clienteAlvo) {

		Bundle bd = new Bundle();
		bd.putSerializable("clienteAlvo", clienteAlvo);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				atualizarInterface(msg);
			}
		};

		ThreadAmizadesAcoes acaoAmizade = new ThreadAmizadesAcoes(handler,
				Amigos.ENVIAR_SOLICITACAO, bd);
		acaoAmizade.start();

	}

	protected void atualizarInterface(Message msg) {
		// TODO Auto-generated method stub

		switch (msg.what) {

		case ThreadAmizadesAcoes.EXECUTANDO:

			pd = new ProgressDialog(this);

			pd.setMessage("Enviando...");
			pd.show();

			break;

		case ThreadAmizadesAcoes.EXIBINDO:

			View v = getLayoutInflater().inflate(
					R.layout.progress_bar_custom_view, null);

			ImageView imgViewProgDialog = (ImageView) v
					.findViewById(R.id.imgViewProgDialog);

			TextView txtProgDialog = (TextView) v
					.findViewById(R.id.txtProgDialog);

			pd.setContentView(v);

			Bundle bundle = (Bundle) msg.getData();

			boolean sucesso = bundle.getBoolean("sucesso");

			if (sucesso) {
				imgViewProgDialog
						.setImageResource(R.drawable.abc_ic_cab_done_holo_dark);
			}
			txtProgDialog.setText(bundle.getString("mensagem"));

			break;

		case ThreadAmizadesAcoes.CONCLUIDO:

			pd.dismiss();
			break;

		}

	}

}

class RefreshingThread extends Thread {

	Handler hand;

	public RefreshingThread(Handler hand) {

		this.hand = hand;

	}

	@Override
	public void run() {
		// TODO Auto-generated method stub

		Message msg = new Message();

		Bundle bundle = new Bundle();

		msg.what = ThreadAmizadesAcoes.EXECUTANDO;

		hand.sendMessage(msg);

		Message mensagem = new Message();

		ArrayList<Cliente> listaDeClientes = WsServicos.listarClientes();

		bundle.putSerializable("listaDeClientes", listaDeClientes);

		mensagem.setData(bundle);

		mensagem.what = ThreadAmizadesAcoes.EXIBINDO;

		hand.sendMessage(mensagem);

	}
}
